/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.boot.web.thread;

import com.alibaba.ttl.TtlCallable;
import com.alibaba.ttl.TtlRunnable;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import org.slf4j.MDC;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * 异步线程池（解决线程变量共享）.
 *
 * @author zengdegui
 * @since 2023/08/29 21:28
 */
public class TtlThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {

    @Override
    public void execute(Runnable task) {
        Runnable runnable = TtlThreadPoolTaskExecutor.wrap(TtlRunnable.get(task));
        super.execute(runnable);
    }

    @Override
    public <T> Future<T> submit(Callable<T> task) {
        Callable<T> callable = TtlThreadPoolTaskExecutor.wrap(TtlCallable.get(task));
        return super.submit(callable);
    }

    @Override
    public Future<?> submit(Runnable task) {
        Runnable runnable = TtlThreadPoolTaskExecutor.wrap(TtlRunnable.get(task));
        return super.submit(runnable);
    }

    @Override
    protected void cancelRemainingTask(Runnable task) {
        Runnable runnable = TtlThreadPoolTaskExecutor.wrap(TtlRunnable.get(task));
        super.cancelRemainingTask(runnable);
    }

    /**
     * 包装线程池任务.
     *
     * @param callable 回调任务
     * @param <T>      泛型
     * @return Callable<T>
     */
    static <T> Callable<T> wrap(final Callable<T> callable) {
        Map<String, String> context = getMdcMap();
        return () -> {
            if (Objects.nonNull(context)) {
                MDC.setContextMap(context);
            }
            try {
                return callable.call();
            } finally {
                if (Objects.nonNull(context)) {
                    MDC.clear();
                }
            }
        };
    }

    /**
     * 包装线程池任务.
     *
     * @param runnable 运行任务
     * @return runnable
     */
    static Runnable wrap(final Runnable runnable) {
        Map<String, String> context = getMdcMap();
        return () -> {
            if (Objects.nonNull(context)) {
                MDC.setContextMap(context);
            }
            try {
                runnable.run();
            } finally {
                if (Objects.nonNull(context)) {
                    MDC.clear();
                }
            }
        };
    }

    private static Map<String, String> getMdcMap() {
        return MDC.getCopyOfContextMap();
    }
}
